package com.reliable.service.apiclient;

import cn.hutool.json.ObjectMapper;
import com.reliable.api.dto.address.CountryInfo;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;


import javax.net.ssl.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

/**
 * @author yuyantao
 * ClassName: ApiClientService
 * date: 2025/8/19 11:58
 */
@Service
public class ApiClientService {

    private final OkHttpClient client;



    /**
     * 查询域名WHOIS信息（安全版本）
     * @param domain 域名
     * @return WHOIS信息JSON字符串
     */
    public String queryWhois(String domain) {
        String url = "https://v2.xxapi.cn/api/whois?domain=" + domain;

        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                return response.body().string();
            } else {
                throw new RuntimeException("API调用失败: HTTP " + response.code());
            }
        } catch (IOException e) {
            throw new RuntimeException("查询WHOIS信息失败: " + e.getMessage(), e);
        }
    }





    public ApiClientService() {
        // 初始化 OkHttpClient 并解决 SSL 证书问题
        try {
            // 创建信任所有证书的 TrustManager
            final TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {
                            // 不检查客户端证书
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {
                            // 不检查服务器证书
                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[]{};
                        }
                    }
            };

            // 创建 SSLContext
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // 创建 HostnameVerifier
            HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true; // 跳过主机名验证
                }
            };

            // 构建 OkHttpClient
            client = new OkHttpClient.Builder()
                    .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0])
                    .hostnameVerifier(hostnameVerifier)
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .build();

        } catch (Exception e) {
            throw new RuntimeException("Failed to create OkHttpClient with SSL bypass", e);
        }    }

}
